package com.sooth.common.dream.handler;


import cn.hutool.core.collection.CollUtil;
import com.dream.mate.permission.inject.PermissionHandler;
import com.dream.system.config.MethodInfo;
import com.dream.system.table.TableInfo;
import com.sooth.common.core.domain.model.LoginUser;
import com.sooth.common.dream.annotation.IgnorePermission;
import com.sooth.common.satoken.utils.LoginHelper;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

public class SoothPermissionHandler implements PermissionHandler {
    @Override
    public boolean isPermissionInject(MethodInfo methodInfo, TableInfo tableInfo) {
        boolean ignorePermission = false;
        Method method = methodInfo.getMethod();
        if (method != null) {
            ignorePermission = method.getAnnotation(IgnorePermission.class) != null || method.getDeclaringClass().getAnnotation(IgnorePermission.class) != null;
        }
        return !ignorePermission && tableInfo.getType().getAnnotation(IgnorePermission.class) == null && tableInfo.getColumnInfo("deptId") != null;
    }

    @Override
    public String getPermission(String alias) {
        if (LoginHelper.isSuperAdmin()) {
            return "1=1";
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<Long> deptIds = loginUser.getDeptIds();
        String customDeptSql = null;
        if (CollUtil.isNotEmpty(deptIds)) {
            customDeptSql = alias + ".dept_id in (" + String.join(",", deptIds.stream().map(deptId -> String.valueOf(deptId)).collect(Collectors.toList())) + ")";
        }
        Integer dataScope = loginUser.getDataScope();
        switch (dataScope) {
            case 1:
                return "1=1";
            case 2:
                if (customDeptSql == null) {
                    return "1<>1";
                }
                return customDeptSql;
            case 3:
                if (customDeptSql != null) {
                    return customDeptSql + " or " + alias + ".dept_id=" + loginUser.getDeptId();
                }
                return alias + ".dept_id=" + loginUser.getDeptId();
            case 4:
                if (customDeptSql != null) {
                    return customDeptSql + " or " + alias + ".dept_id=" + loginUser.getDeptId() + " and " + alias + ".create_by=" + loginUser.getUserId();
                }
                return alias + ".dept_id=" + loginUser.getDeptId() + " and " + alias + ".create_by=" + loginUser.getUserId();
            default:
                if (customDeptSql != null) {
                    return customDeptSql;
                }
                return "1<>1";
        }
    }
}
